<template>
  <el-dialog v-model="dialogVisible" :appendToBody="true" title="发送优惠券" width="70%">
    <!-- 搜索工作栏 -->
    <el-card shadow="hover">
      <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px" label-width="82px">
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="queryParams.name" class="!w-240px" placeholder="请输入优惠劵名" clearable @keyup="handleQuery" />
        </el-form-item>
        <el-form-item label="业务类型" prop="businessType">
          <el-select v-model="queryParams.businessType" placeholder="请选择业务类型" clearable>
            <el-option v-for="dict in coupon_business_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="平台类型" prop="plateType">
          <el-select v-model="queryParams.plateType" placeholder="请选择平台类型" clearable>
            <el-option v-for="dict in coupon_plate_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery">
            <Icon class="mr-5px" icon="ep:search" />
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <Icon class="mr-5px" icon="ep:refresh" />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表 -->
    <el-card shadow="never" style="margin-top: 10px">
      <el-table v-loading="loading" :data="list" show-overflow-tooltip>
        <el-table-column align="center" label="优惠券名称" prop="name" min-width="60" />
        <el-table-column label="业务类型" align="center" prop="businessType">
          <template #default="scope">
            <dict-tag :options="coupon_business_type" :value="scope.row.businessType" />
          </template>
        </el-table-column>
        <el-table-column label="平台类型" align="center" prop="plateType">
          <template #default="scope">
            <dict-tag :options="coupon_plate_type" :value="scope.row.plateType" />
          </template>
        </el-table-column>
        <el-table-column label="优惠金额 / 折扣" align="center" prop="discount" :formatter="discountFormat" min-width="60" />
        <el-table-column align="center" label="最低消费" prop="usePrice" min-width="60" :formatter="usePriceFormat" />
        <el-table-column align="center" label="有效期限" prop="validityType" min-width="140" :formatter="validityTypeFormat" />
        <el-table-column align="center" label="剩余数量" min-width="60" :formatter="remainedCountFormat" />
        <el-table-column align="center" label="备注" prop="remark" min-width="60" />
        <el-table-column label="操作" align="center" min-width="60px" fixed="right">
          <template #default="scope">
            <el-button
              link
              type="primary"
              :disabled="sendLoading"
              :loading="sendLoading"
              @click="handleSendCoupon(scope.row)"
              v-hasPermi="['tearoom:coupon:send']"
            >
              发送
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <div class="clear-both"></div>
  </el-dialog>
</template>
<script lang="ts" setup>
import { listCouponTemplate } from '@/api/tearoom/couponTemplate/index';
import { sendCoupon } from '@/api/tearoom/coupon/index';
import { CouponTemplateTakeTypeEnum } from '@/api/tearoom/couponTemplate/types';
import { CouponForm } from '@/api/tearoom/coupon/types';
import {
  discountFormat,
  remainedCountFormat,
  takeLimitCountFormat,
  validityTypeFormat,
  usePriceFormat
} from '@/views/tearoom/couponTemplate/formatter';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { coupon_plate_type,coupon_business_type } = toRefs<any>(proxy?.useDict('coupon_plate_type','coupon_business_type'));
defineOptions({ name: 'PromotionCouponSendForm' });
const total = ref(0); // 列表的总页数
const list = ref<any[]>([]); // 列表的数据
const loading = ref(false); // 列表的加载中
const sendLoading = ref(false); // 发送按钮的加载中
const dialogVisible = ref(false); // 弹窗的是否展示
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  name: null,
  plateType: 1,
  businessType:undefined,
  canTakeTypes: [CouponTemplateTakeTypeEnum.ADMIN.type]
}); // 查询参数
const queryFormRef = ref(); // 搜索的表单
// 领取人的编号列表
let userIds: number[] = [];

/** 打开弹窗 */
const open = (ids: number[]) => {
  userIds = ids;
  // 打开时重置查询，防止发送列表剩余数量未更新的问题
  resetQuery();
  dialogVisible.value = true;
};
defineExpose({ open }); // 提供 open 方法，用于打开弹窗

/** 查询列表 */
const getList = async () => {
  loading.value = true;
  try {
    const data = await listCouponTemplate(queryParams.value);
    list.value = data.rows;
    total.value = data.total;
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef?.value?.resetFields();
  handleQuery();
};

/** 发送操作 **/
const handleSendCoupon = async (item) => {
  try {
    // 新增：弹出备注输入框
    const { value: remark } = await ElMessageBox.prompt('请输入备注（选填）', '发送优惠券', {
      confirmButtonText: '发送',
      cancelButtonText: '取消',
      inputType: 'textarea',
      inputValue: item.remark || '', // 设置模板备注为默认值
      inputPlaceholder: '请输入给用户的备注信息...',
      inputValidator: (value) => {
        if (value && value.length > 200) {
          return '备注长度不能超过200个字符';
        }
        return true;
      }
    }).catch(() => {
      return { value: undefined };
    }); // 处理取消操作

    // 如果用户点击取消，直接返回
    if (remark === undefined) return;

    sendLoading.value = true;
    const initFormData: CouponForm = {
      templateId: item.id,
      userIds: userIds,
      remark: remark || '' // 新增备注字段
    };
    await sendCoupon(initFormData);
    // 提示
    proxy?.$modal.msgSuccess('发送成功');
    dialogVisible.value = false;
  } finally {
    sendLoading.value = false;
  }
};
</script>
